package com.rjt.article.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rjt.article.model.ArticleCommentModel;
import com.rjt.article.model.ArticleContentModel;
import com.rjt.article.model.ArticleModel;
import com.rjt.article.model.ArticleNumModel;
import com.rjt.article.service.ArticleCircleShareService;
import com.rjt.article.service.ArticleCommentService;
import com.rjt.article.service.ArticleContentService;
import com.rjt.article.service.ArticleFriendsShareService;
import com.rjt.article.service.ArticleNumService;
import com.rjt.article.service.ArticleService;
import com.rjt.article.service.ArticleVisitService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

@Controller
public class ArticleWxController {
	
	@Autowired
	private WxMpService wxMpService;


	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private ArticleContentService articleConentService;
	
	@Autowired
	private ArticleNumService articleNumService;
	
	@Autowired
	private ArticleCommentService articleCommentService;
	

	@Autowired
	private ArticleVisitService articleVisitService;
	
	@Autowired
	private ArticleFriendsShareService articleFriendsShareService;
	
	@Autowired
	private ArticleCircleShareService articleCircleShareService;

	@Value("${wechat.oauthUrl}")
	private String oauthUrl;

	

	/**
	 * 授权的接口
	 *  code 只能 用一次，用完之后，应该重新授权，或者直接将openId存储起来，毕竟不是变化的
	 *  {"errcode":40163,"errmsg":"code been used, hints: [ req_id: 94nUVa0268sha1 ]"}
	 *  
	 * @param code
	 * @param model
	 * @return
	 * @throws WxErrorException
	 */
	@GetMapping("oauth")
	public String oauth(String code, Model model,String state,HttpServletRequest request,HttpServletResponse response)  {
	    try {
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
			boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
			if (!valid) {
				wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
			}
			wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
			Cookie cookie=new Cookie("openId", wxMpOAuth2AccessToken.getOpenId());
			cookie.setDomain(oauthUrl.replace("http://", ""));
			cookie.setPath("/");
			cookie.setMaxAge(365 * 24 * 60 * 60);
			response.addCookie(cookie);
		} catch (WxErrorException e) {
			// TODO: handle exception
			System.out.println("发生错误，重新授权"+e.getMessage());
			
		}
		return "redirect:"+oauthUrl+"/"+state;
	}

	
	@GetMapping("{id}")
	public String index(@PathVariable(value="id") String id,HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("openId")) {
					try {
						if(!Objects.equals(cookies[i].getValue(), null)) {
							ArticleModel articleModel = articleService.findById(id);
							if(articleModel==null) {
								return "common/error";
							}
							request.setAttribute("title", articleModel.getTitle());
							request.setAttribute("desc", articleModel.getDescribe());
							request.setAttribute("imgUrl", articleModel.getImgUrl());
							request.setAttribute("id", articleModel.getId());
							 StringBuilder sb=new StringBuilder("http://");
							 sb.append(request.getServerName());
							 if(request.getServerPort()!=80) {
								 sb.append(":");
								 sb.append(request.getServerPort());
							 }
							 sb.append(request.getContextPath());
							 sb.append(request.getServletPath());
							 if(request.getQueryString()!=null) {
								 sb.append("?"); 
								 sb.append(request.getQueryString());
							 }
							WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(sb.toString());
							request.setAttribute("jsapiSignature", jsapiSignature);
							request.setAttribute("link", sb.toString());
							return "weixin/index";
						}
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("发生错误，不能分享"+e.getMessage());
					}
				}
			}
		}	
		String url = oauthUrl + "/oauth";
		String urlX = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, id);
		return "redirect:" + urlX;
		
		
	}
	
	
	@GetMapping("getContent")
	public String getContent(HttpServletRequest request,String id) {
		
		ArticleContentModel articleContentModel = articleConentService.findById(id);
		request.setAttribute("id", articleContentModel.getId());
		request.setAttribute("title", articleContentModel.getTitle());
		request.setAttribute("js_name", articleContentModel.getAuthor());
		request.setAttribute("js_content",articleContentModel.getContent());
		request.setAttribute("publishTime", articleContentModel.getCreateDate().getTime()/1000);
		request.setAttribute("openRead", articleContentModel.getOpenRead());
		request.setAttribute("openComment", articleContentModel.getOpenComment());
		request.setAttribute("publishDate", new SimpleDateFormat("yyyy-MM-dd").format(articleContentModel.getCreateDate()));
		return "weixin/content";
	}
	@GetMapping("getComments")
	@ResponseBody
	public List<ArticleCommentModel> getComments(String rId,HttpServletRequest request) {
		articleVisitService.save(rId,request);
		return articleCommentService.findByRId(rId);
	}
	
	
	@GetMapping("getReadNum")
	@ResponseBody
	public ArticleNumModel getReadNum(String id,HttpServletRequest request) {
		  ArticleNumModel articleNumModel = articleNumService.findById(id);
		  if(articleNumModel.getLikeNum().length()>4) {
			  int linkNum = Integer.parseInt(articleNumModel.getLikeNum());
			  BigDecimal count = new BigDecimal(linkNum);
			  BigDecimal result = count.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
			  articleNumModel.setLikeNum(result+"万");
		  }
		  if(articleNumModel.getReadNum().length()>4) {
			  int readNum = Integer.parseInt(articleNumModel.getReadNum());
			  BigDecimal count = new BigDecimal(readNum);
			  BigDecimal result = count.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
			  articleNumModel.setReadNum(result+"万");
		  }
		  return articleNumModel;
	}
	
	@PostMapping("addFriendsNum")
	@ResponseBody
	public void friendsNum(String id,HttpServletRequest request) {
		articleFriendsShareService.save(id,request);
	}
	
	@PostMapping("addCircleNum")
	@ResponseBody
	public void circleNum(String id,HttpServletRequest request) {
		articleCircleShareService.save(id,request);
	}
}
